const express = require("express");
const router = express.Router();
const { Category } = require("../../models");
const { success, failure } = require("../../utils/response");
const { Op } = require("sequelize");
const {Conflict,NotFound} = require('http-errors')
const {delKey} = require("../../utils/redis")

// 获取列表全部数据
router.get("/", async (req, res) => {
  try {
    const categories = await Category.findAll();
    success(res, "获取分类列表成功", categories);
  } catch (error) {
    failure(res, error);
  }
});

// 添加分类数据
router.post("/", async (req, res) => {
  try {
    const body = await filterBody(req);
    const category = await Category.create(body);
    await delKey('category')
    success(res, "添加分类成功", category);
  } catch (error) {
    failure(res, error);
  }
});

// 删除分类数据
router.delete("/:id", async (req, res) => {
  try {
    const category = await getCategory(req);
    const count = await course.count({where:{categoryId:req.params.id}});
    if(count > 0){
      // 这里应该用409状态码：Conflict 也就是冲突的意思
      // throw new Error("当前分类有课程，无法删除。")
      throw new Conflict('当前分类有课程，无法删除。')
    }
    await category.destroy();
    await delKey('category')
    success(res, "删除分类成功");
  } catch (error) {
    failure(res, error);
  }
});
// 更新分类数据
router.put("/:id", async (req, res) => {
  try {
    const body = await filterBody(req);
    const category = await getCategory(req);
    await category.update(body);
    await delKey('category')
    success(res, "更新分类成功", category);
  } catch (error) {
    failure(res, error);
  }
});

// 模糊查询搜索
router.get("/search", async (req, res) => {
  try {
    const query = req.query;

    const condition = {
      where:{},
      order: [["rank", "ASC"]],
    };
    if (query.name) {
      condition.where.name = {
        [Op.like]: `%${query.name}%`,
      };
    }
    const categories = await Category.findAll(condition);
    success(res, "分类查询成功", categories);
  } catch (error) {
    failure(res, error);
  }
});

// 获取分类详情
router.get("/:id", async (req, res) => {
  try {
    const category = await getCategory(req);
    success(res, "获取分类详情成功", category);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法：白名单过滤
 * @param {*} req
 * @returns
 */
async function filterBody(req) {
  const body = {
    name: req.body.name,
    rank: req.body.rank,
  };
  return body;
}

/**
 * 公共方法：获取当前分类数据
 * @param {*} req
 * @returns
 */
async function getCategory(req) {
  const { id } = req.params;
  const condition = {
    include:[
      {
        model:course,
        as:"courses"
      }
    ]
  }
  const category = await Category.findByPk(id,condition);
  if (!category) {
    throw new NotFound("分类不存在");
  }
  return category;
}

module.exports = router;
